package org.farm.controller;

import com.aliyun.sdk.service.iot20180120.AsyncClient;
import com.google.gson.Gson;
import org.farm.config.AliyunIotConfig;
import org.farm.pojo.ResultVo;
import org.farm.pojo.TempHumidityData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;
import com.aliyun.sdk.service.iot20180120.models.PubResponse;
import java.util.concurrent.ExecutionException;

@EnableAsync
@RestController
@RequestMapping("pub")
public class StatusController {

    @Autowired
    private AliyunIotConfig aliyunIotConfig;

    @GetMapping("/light/{status}")
    public ResultVo light(@PathVariable("status") int status) throws ExecutionException, InterruptedException {

//        int status = function.getStatus();

        try {
            AsyncClient client = aliyunIotConfig.createClient();
            PubResponse resp = aliyunIotConfig.publishMessageLight(client, status);

            System.out.println(new Gson().toJson(resp));
            client.close();

            if (status < 0 || status > 1) {
                return ResultVo.fail("无效的灯光状态", null);
            }else if(status == 1) {
                return ResultVo.success("成功开启灯光", resp);
            }

            return ResultVo.success("成功关闭灯光", resp);

        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return ResultVo.fail("开启灯光失败", e.getMessage());
        }
    }
    @GetMapping("/water{id}")
    public ResultVo water( @PathVariable("status") int status){

//        int status = function.getStatus();

        try {
            AsyncClient client = aliyunIotConfig.createClient();
            PubResponse resp = aliyunIotConfig.publishMessageWater(client,status);

            System.out.println(new Gson().toJson(resp));
            client.close();

            return ResultVo.success("success", resp);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return ResultVo.fail("fail", e.getMessage());
        }
    }

    @GetMapping("/getTempAndHumidity")
    public TempHumidityData getTempAndHumidity() {

        try {
            return aliyunIotConfig.getTemperatureAndHumidity();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
